//
//  SearchTableViewController.m
//  MoeFM
//
//  Created by miyang on 14-11-13.
//  Copyright (c) 2014年 StraightJet. All rights reserved.
//

#import "SearchTableViewController.h"
#import "Favs.h"

#define SEARCH_WIKI_URL @"http://api.moefou.org/search/wiki.json"
#define SEARCH_SUB_URL @"http://api.moefou.org/search/sub.json"



typedef NS_ENUM(int, SearchType) {
    SearchTypeMusic,
    SearchTypeSong
};

@interface SearchTableViewController ()<UISearchBarDelegate>
@property (nonatomic,assign)int searchtype;

@property (nonatomic,assign)BOOL musicSearched;
@property (nonatomic,assign)BOOL songSearched;

@end

@implementation SearchTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        _musicarr = [[NSMutableArray alloc] init];
        _songarr = [[NSMutableArray alloc] init];
        _clearView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
        _clearView.backgroundColor = [UIColor clearColor];
        _searchtype = SearchTypeMusic;
        _musicSearched = NO;
        _songSearched = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UISearchBar *search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    search.searchBarStyle = UIBarStyleDefault;
    search.placeholder = @"搜索                         ";
    search.delegate = self;
    //去除搜索栏背景
    [self searchBarClear:search];
    _searchBar = search;
    search.autocorrectionType = UITextAutocorrectionTypeNo;//取消自动更正
 
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    [searchView addSubview:search];
    self.navigationItem.titleView = searchView;
    self.navigationItem.titleView.backgroundColor = [UIColor clearColor];
    
    
    UIButton *randomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [randomBtn setTitle:@"专辑" forState:UIControlStateNormal];
    randomBtn.frame = CGRectMake(20, 0, 139.5, 30);
//    randomBtn.backgroundColor = [UIColor blackColor];
    [randomBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [randomBtn addTarget:self action:@selector(musicTable) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *lineView = [[UIImageView alloc] initWithFrame:CGRectMake(159.5, 5, 1, 20)];
    [lineView setImage:[UIImage imageNamed:@"line.png"]];
    
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setTitle:@"曲目" forState:UIControlStateNormal];
    searchBtn.frame = CGRectMake(160.5, 0, 139.5, 30);
//    searchBtn.backgroundColor = [UIColor blackColor];
    [searchBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(songTable) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [headView addSubview:randomBtn];
    [headView addSubview:lineView];
    [headView addSubview:searchBtn];
    
    self.tableView.tableHeaderView = headView;
    
    
}

- (void)musicTable
{
    _showarr = _musicarr;
    _searchtype = SearchTypeMusic;
    if (![_searchBar.text isEqualToString:@""] && _musicSearched == NO) {
        [self SearchItemWithKeyword:_searchBar.text andType:@"music" andURLType:SEARCH_WIKI_URL];
    } else {
        [self.tableView reloadData];
    }
    
}

- (void)songTable
{
    _showarr = _songarr;
    _searchtype = SearchTypeSong;
    if (![_searchBar.text isEqualToString:@""] && _songSearched == NO) {
        [self SearchItemWithKeyword:_searchBar.text andType:@"song" andURLType:SEARCH_SUB_URL];
    } else {
        [self.tableView reloadData];
    }
}

#pragma mark-去除searchbar背景色
- (void)searchBarClear:(UISearchBar *)searchBar
{
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    
    if ([searchBar respondsToSelector:@selector(barTintColor)]) {
        
        float  iosversion7_1 = 7.1 ;
        
        if (version >= iosversion7_1)
        {
            //iOS7.1
            [[[[searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
            [searchBar setBackgroundColor:[UIColor clearColor]];
        }else
        {
            //iOS7.0
            [searchBar setBarTintColor:[UIColor clearColor]];
            [searchBar setBackgroundColor:[UIColor clearColor]];
        }
        
    }
    else
    {
        //iOS7.0 以下
        [[searchBar.subviews objectAtIndex:0] removeFromSuperview];
        [searchBar setBackgroundColor:[ UIColor clearColor]];
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

        return self.showarr.count;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collection"];
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"collection"];
    }
    
    if (_searchtype == SearchTypeMusic) {
        Favs *fav = [[Favs alloc] init];
        fav = [_showarr objectAtIndex:indexPath.row];
        cell.textLabel.text = fav.wiki_title;
    } else if (_searchtype == SearchTypeSong) {
        Sub *subItem = [[Sub alloc] init];
        subItem = [_showarr objectAtIndex:indexPath.row];
        cell.textLabel.text = subItem.sub_title;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSelector:@selector(deselect) withObject:nil afterDelay:0.2f];
    
    if (_searchtype == SearchTypeMusic)
    {
        Favs *pass = [[Favs alloc] init];
        pass = [_musicarr objectAtIndex:indexPath.row];
        NSString *urlStr = [NSString stringWithFormat:MUSIC_URL,pass.wiki_id];
        //        NSString *albumStr = [NSString stringWithFormat:@"%@",pass.wiki_title];
        [[PlayerViewController sharPlayer] playingWithURL:urlStr andAlbumTitle:@"搜索专辑"];
    } else {
        //NSMutableArray *subarr = [[NSMutableArray alloc] init];
        NSString *substr = [[NSString alloc] init];
        
        for (NSInteger i = indexPath.row; i < _showarr.count; i++) {
            Sub *subItem = [[Sub alloc] init];
            subItem = [_showarr objectAtIndex:i];
            //[subarr addObject:[NSString stringWithFormat:@"%ld",subItem.sub_id]];
            substr = [substr stringByAppendingFormat:@"%@,",subItem.sub_id];
        }
        NSString *urlStr = [NSString stringWithFormat:SONG_URL,substr];
        //        NSString *albumStr = @"单曲";
        [[PlayerViewController sharPlayer] playingWithURL:urlStr andAlbumTitle:@"搜索单曲"];
    }
}



#pragma mark-搜索代理
//开始编辑
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //NSLog(@"searchbarshouldbeginediting");
    
    //点击空白处取消键盘
    [self.tableView addSubview:_clearView];
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    _clearView.userInteractionEnabled = YES;
    tapGr.cancelsTouchesInView = NO;
    [self.clearView addGestureRecognizer:tapGr];
    
    return YES;
}

//点击空白处取消键盘
-(void)viewTapped:(UITapGestureRecognizer*)tapGr{
    //NSLog(@"viewtapped");
    [_clearView removeFromSuperview];
    [_searchBar resignFirstResponder];
    
}

//点击搜索键之后
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (searchBar.text == nil) {
    }
    [MBProgressHUD showMessage:@"努力加载中....."];
    [_clearView removeFromSuperview];
    [searchBar resignFirstResponder];
    if (_searchtype == SearchTypeMusic) {
        _musicSearched = YES;
        [self SearchItemWithKeyword:searchBar.text andType:@"music" andURLType:SEARCH_WIKI_URL];
    } else if (_searchtype == SearchTypeSong) {
        _songSearched = YES;
        [self SearchItemWithKeyword:searchBar.text andType:@"music" andURLType:SEARCH_SUB_URL];
    }
}

//点击取消键之后
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [_clearView removeFromSuperview];
    //NSLog(@"cancelButton");
}
//完成文字输入
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [_clearView removeFromSuperview];
    if (searchBar.text == nil) {
        
        return YES;
    }
    return YES;
}
- (void)SearchItemWithKeyword:(NSString *)keyword andType:(NSString *)type andURLType:(NSString *)URLType
{
    NSString *urlstr = [NSString stringWithFormat:@"%@?keyword=%@&wiki_type=%@&page=1&perpage=50&api_key=c6a6e84b505673382843850f8bed723d0545770eb",URLType,keyword,type];
    urlstr = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURL *url = [NSURL  URLWithString:urlstr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [_showarr removeAllObjects];
        
        [MBProgressHUD hideHUD];
        
        NSDictionary *response = [responseObject objectForKey:@"response"];
        
        NSDictionary *information = [response objectForKey:@"information"];
        NSString *countstr = [information objectForKey:@"count"];
        NSInteger count = [countstr integerValue];
        
        if (_searchtype == SearchTypeMusic) {
            
            NSArray *wikis = [response objectForKey:@"wikis"];
            if (count != 0) {
                for (NSDictionary *tempDic in wikis) {
                    Favs *temp  = [[Favs alloc] init];
                    temp.wiki_id = [tempDic objectForKey:@"wiki_id"];
                    temp.wiki_name = [tempDic objectForKey:@"wiki_name"];
                    temp.wiki_title = [tempDic objectForKey:@"wiki_title"];
                    temp.wiki_meta = [tempDic objectForKey:@"wiki_meta"];
                    temp.wiki_cover = [tempDic objectForKey:@"wiki_cover"];
                    [_musicarr addObject:temp];
                    
                }
                _showarr =_musicarr;
            } else {
                [_showarr removeAllObjects];
            }
            
            
        } else if (_searchtype == SearchTypeSong) {
            NSArray *subs = [response objectForKey:@"subs"];
            
            if (count != 0) {
                for (NSDictionary *subDic in subs) {
                    Sub *subItem = [[Sub alloc] init];
                    subItem.sub_id = [subDic objectForKey:@"sub_id"];
                    subItem.sub_parent_wiki = [subDic objectForKey:@"sub_parent_wiki"];
                    subItem.sub_title = [subDic objectForKey:@"sub_title"];
                    subItem.sub_order = [subDic objectForKey:@"sub_order"];
                    subItem.sub_meta = [subDic objectForKey:@"sub_meta"];
                    subItem.wiki_dic = [subDic objectForKey:@"wiki"];
                    [_songarr addObject:subItem];
                }
                _showarr = _songarr;
            } else {
                [_showarr removeAllObjects];
            }
        }
        
        [self.tableView reloadData];
        NSLog(@"%@ search success",type);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    [[NSOperationQueue mainQueue] addOperation:op];
}
    
- (void)deselect
{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
